package xxh;

import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.util.HashMap;

public class ReturnProcess extends Component {
    private Connection connection;

    // 构造函数，传入 JComboBox 和用户编号
    ReturnProcess(JComboBox<String> cmbBookNo,String Uno) throws SQLException {
        connection = ConnectDB.getConnection();
        if (connection != null) {
            loadBookNumbers(cmbBookNo,Uno);  // 加载借阅但未归还的书籍
        } else {
            JOptionPane.showMessageDialog(this, "数据库连接失败！", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 加载借阅但未归还的书籍
    private void loadBookNumbers(JComboBox<String> cmbBookNo, String userNo) throws SQLException {
        // 选择借阅且未归还的书籍
        PreparedStatement preparedStatement = connection.prepareStatement(
                "SELECT books.Bno, books.Bname " +
                        "FROM lend " +
                        "JOIN books ON lend.Bno = books.Bno " +
                        "WHERE lend.Uno = ? AND lend.Backtime IS NULL");

        preparedStatement.setString(1, userNo);  // 设置用户编号参数
        ResultSet rs = preparedStatement.executeQuery();

        HashMap<String, String> bookMap = new HashMap<>();
        while (rs.next()) {
            String bno = rs.getString("Bno");
            String bname = rs.getString("Bname");
            bookMap.put(bno, bname);
            cmbBookNo.addItem(bno);
        }

        // 设置 JComboBox 的渲染器显示书籍编号和书名
        cmbBookNo.setRenderer((JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus) -> {
            JLabel label = new JLabel();
            if (value != null) {
                String bookName = bookMap.get(value);  // 获取书名
                label.setText(value + " - " + bookName);  // 显示 "Bno - Bname"
            }
            if (isSelected) {
                label.setBackground(list.getSelectionBackground());
                label.setForeground(list.getSelectionForeground());
                label.setOpaque(true);
            }
            return label;
        });

        rs.close();
        preparedStatement.close();
    }

    // 归还书籍的方法
    public boolean returnBook(String userNo, String bookNo) throws SQLException {
        PreparedStatement pstmt = connection.prepareStatement(
                "UPDATE lend SET Backtime = ? WHERE Bno = ? AND Uno = ? AND Backtime IS NULL");

        pstmt.setDate(1, java.sql.Date.valueOf(java.time.LocalDate.now()));  // 设置当前日期作为归还时间
        pstmt.setString(2, bookNo);  // 设置书籍编号
        pstmt.setString(3, userNo);  // 设置用户编号

        int ans = pstmt.executeUpdate();

        // 如果更新成功，更新书籍数量
        if (ans == 1) {
            pstmt = connection.prepareStatement("UPDATE books SET Bnumber = Bnumber + 1 WHERE Bno = ?");
            pstmt.setString(1, bookNo);
            int updateCount = pstmt.executeUpdate();
        }

        pstmt.close();
        return ans == 1;  // 返回是否更新成功
    }
}
